package com.naiterui.ehp.bs.patient.config;

import javax.annotation.PostConstruct;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.wechat.service.IAccessTokenService;
import com.naiterui.ehp.bs.wechat.utils.WeChatApiUtil;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * @author gaoliangliang
 * @date 2021-04-27 16:12
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConfigurationProperties(prefix = "button")
public class MenuConfig {

    private final IAccessTokenService accessTokenService;
    private final ConfigService configService;

    @SneakyThrows
    @PostConstruct
    public void init() {
        String initJson = configService.getConfig("weixin-menu.json", "DEFAULT_GROUP", 5000);

        try {
            updateMenu(initJson);
            // 开户监听，实现动态
            configService.addListener("weixin-menu.json", "DEFAULT_GROUP", new AbstractListener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("更新微信菜单");
                    updateMenu(configInfo);
                    log.info("更新微信菜单");
                }
            });
        } catch (Exception e) {
            log.warn("MenuConfig Initializing ERROR ", e);
        }

    }

    private void updateMenu(String initJson) {
        // 初始化菜单JSON
        String menuJson = WeChatApiUtil.getMenu(accessTokenService.accessToken());

        initJson = initJson.replaceAll("\\$\\{wx_miniapp_app_id}", ConfigUtil.getString("wx_miniapp_app_id"));
        log.info("MenuConfig currentMenuJson={},initJson={}", menuJson, initJson);

        String createResult = WeChatApiUtil.createMenu(accessTokenService.accessToken(), initJson);
        log.info("MenuConfig createResult={}", createResult);
    }
}
